var express = require('express');
var http = require('http');
var path = require("path");


//路由器
var checkUp = require("./router/dictionary.js");
var useropr = require("./router/usersopr.js");
var cryptor = require("./router/cryptoRouter.js");
var diropr = require("./router/notebook.js");
var tokenopr = require("./router/tokenopr.js");
var app = new express();


var logger = require("morgan");

//环境变量
const env = require("./classes/env.js").setParameterOfServer();



//设置允许跨域访问该服务.
app.all('*', function(req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", env.originUrl);    
    res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, token");
    res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");//"PUT,POST,GET,DELETE,OPTIONS"
    res.setHeader("Access-Control-Allow-Credentials", true);
    res.setHeader("X-Powered-By",'Express');
    res.setHeader("Content-Type", "application/json;charset=utf-8");
    // res.setHeader("Content-Type", "text/html;charset=utf-8");

    next();
});

app.use( logger("short") );

var pathStatic = path.resolve(__dirname , "client/deploy/dist");
app.use( express.static(pathStatic) );

/****************** 
以下 为html模板引擎的使用
*/
// var ejs = require('ejs');
// // view engine setup
// app.set('views', path.join(__dirname, 'client/deploy/dist'));
// app.engine('html', require('ejs').__express);  
// app.set('view engine', 'html');
// /* GET page. */

// app.use('/editor', function(req, res, next) {
//     res.type('html');
//     res.render('editor');
    
//   });
/*
以上 为html模板引擎的使用
********************* */
let apending = env.appending;
// dictionay router
app.use(apending+"/dict", checkUp);

//关于用户的操作
app.use(apending+"/user", useropr);

//加密的操作
app.use(apending+"/crypto", cryptor);

//用户笔记接口
app.use(apending+"/note", diropr);

//token接口
app.use(apending+"/token",tokenopr);

// error handling 
// app.use(function(err , req , res , next){
//     if(err){
//         // console.log(err);// or record this issue;
//         res.statusCode = 500;
//         res.send("Internal server problem.");
//         res.end();
//     }
//     next(); 
// });

//404 not found request
app.use(function(req , res){
    res.statusCode = 404;
    res.send("page was not found.");
    res.end();
}); 

http.createServer(app).listen(3000);
